//
//  ZZCRequest.m
//  ZZC-Finance
//
//  Created by mac on 2017/6/9.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCRequest.h"

@interface ZZCRequest ()

///网络请求的管理器
@property (nonatomic, strong) AFHTTPSessionManager *sessionManager;

@end
@implementation ZZCRequest
///
+ (instancetype)sharedNetworkTools {

    static ZZCRequest * _instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
        NSSet *set = [NSSet setWithObjects:@"application/json" ,@"text/plain",@"text/html",@"text/xml",@"text/javascript", @"text/json", nil];
        _instance.sessionManager.responseSerializer.acceptableContentTypes = set;

    });

    return _instance;
}

/// 初始化方法
- (instancetype)init {
    
    if (self = [super init]) {
        self.sessionManager = [[AFHTTPSessionManager alloc] init];
        
    }
    return self;
}

///POST请求
- (void)POST:(NSString *)URLString parameters:(nullable NSDictionary* )parameters finished:(void (^)(id _Nullable responseObject, NSError * _Nullable error)) finshed {
    
        [self.sessionManager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        finshed(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finshed(nil,error);
    }];

}
//支付充值请求
- (void)PAYPOST:(NSString *)URLString parameters:(nullable NSDictionary* )parameters finished:(void (^)(id _Nullable responseObject, NSError * _Nullable error)) finshed {

    //加上这一句即可
    _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [self.sessionManager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        self.sessionManager = [AFHTTPSessionManager manager];

        finshed(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finshed(nil,error);
    }];
    
}


///GET请求
- (void)GET:(NSString *)URLString parameters:(nullable NSDictionary* )parameters finished:(void (^)(id _Nullable responseObject, NSError * _Nullable error)) finshed {
    [self.sessionManager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        finshed(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finshed(nil,error);
    }];
    
}

///图片上传
- (void)uploadWithURL:(NSString *)url
               params:(NSDictionary *)parmas
         formBoundary:(UIImage *)formBoundary
              success:(RequestSuccessBlock)success
                 fail:(RequestFailBlock)fail {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml",@"text/plain",@"multipart/form-data", nil];

    [manager POST:url parameters:parmas constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        
        NSData *imageData = UIImageJPEGRepresentation(formBoundary,0.5);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat =@"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        //上传的参数(上传图片，以文件流的格式)
        [formData appendPartWithFileData:imageData
                                    name:@"file"
                                fileName:fileName
                                mimeType:@"multipart/form-data"];
        
    } progress:^(NSProgress *_Nonnull uploadProgress) {
        //打印下上传进度
    } success:^(NSURLSessionDataTask *_Nonnull task, id _Nullable responseObject) {
        //上传成功
        success(responseObject);
    } failure:^(NSURLSessionDataTask *_Nullable task, NSError * _Nonnull error) {
        //上传失败
        fail(error,nil,nil);
    }];

}


//排序生成sign
+ (NSString *)getSignWithDict:(NSDictionary *)dict{
    NSString *str = @"";
    NSArray *keyArr = [dict allKeys];
    
    NSArray *newArr = [keyArr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    NSString *valueStr = @"";
    NSMutableArray *arr = [NSMutableArray array];
    for (int i = 0; i < newArr.count; i++) {
        valueStr = [NSString stringWithFormat:@"%@=%@",newArr[i],dict[newArr[i]]];
        [arr addObject:valueStr];
    }
    valueStr = [arr componentsJoinedByString:@"&"];
    str = [NSString stringWithFormat:@"%@&app_secret=3ffe170accff4fe1bdc4c1ec08af87dd",valueStr];
    return str;
    
}

@end
